﻿using System;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using RotaractProjectCalendar.DataAccessLayer;
using RotaractProjectCalendar.ViewModels;

namespace RotaractProjectCalendar.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class ProjectController : Controller
    {
        private readonly CalendarContext _db = new CalendarContext();

        //
        // GET: /Admin/Project/
        public ActionResult Index(int? id, int? clubId)
        {
            var viewModel = new ProjectIndexData
            {
                Projects = _db.Projects
                    .OrderBy(p => p.StartDateTime)
            };

            if(id != null)
            {
                ViewBag.ProjectID = id.Value;
                viewModel.Club = viewModel.Projects.Single(p => p.Id == id.Value).Club;
            }

            if (clubId == null)
            {
                return View(viewModel);
            }

            ViewBag.ClubId = clubId.Value;
            viewModel.Coordinator = viewModel.Projects
                .Single(c => id != null && (c.Coordinator.ClubId == clubId.Value && c.Coordinator.Id == c.CoordinatorId && c.Id == id.Value))
                .Coordinator;

            return View(viewModel);
        }

        //
        // GET: /Admin/Project/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if(id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var project = await _db.Projects.FindAsync(id);
            if(project == null)
            {
                return HttpNotFound();
            }
            return View(project);
        }

        //
        // GET: /Admin/Project/Delete/5
        public async Task<ActionResult> Delete(int? id, bool? saveChangesError = false)
        {
            if(id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            if(saveChangesError.GetValueOrDefault())
            {
                ViewBag.ErrorMessage = "Deleted failed. Try again, and if the problem persist see your system administrator.";
            }
            var project = await _db.Projects.FindAsync(id);
            if(project == null)
            {
                return HttpNotFound();
            }
            return View(project);
        }

        //
        // POST: /Admin/Project/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Delete(int id)
        {
            try
            {
                var project = await _db.Projects.FindAsync(id);
                _db.Projects.Remove(project);

                if(!String.IsNullOrWhiteSpace(project.Photo))
                {
                    System.IO.File.Delete(Server.MapPath(project.Photo));
                }

                await _db.SaveChangesAsync();
            }
            catch(RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                return RedirectToAction("Delete", new { id, saveChangesError = true });
            }

            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if(disposing)
            {
                _db.Dispose();
            }
            base.Dispose(disposing);
        }
	}
}